package com.liugenshui.redisdemo.controller;

import com.alibaba.fastjson.JSON;
import com.liugenshui.redisdemo.entity.Test;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Description:
 * @Author: icourt-liugenshui
 * @Date: Create in 2018/10/16 下午12:06
 */
@RestController
@RequestMapping("/api/v1/test")
public class TestController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final String TEST_VALUE_KEY = "test:value:";

    private static final String TEST_LIST_KEY = "test:id:list";

    @GetMapping("/{id}")
    public Test getById(@PathVariable("id") String id) {
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("id不能为空");
        }
        return JSON.parseObject(redisTemplate.opsForValue().get(TEST_VALUE_KEY+id), Test.class);
    }

    @PostMapping
    public String create(@RequestBody Test test) {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForList().rightPush(TEST_LIST_KEY, id);
        test.setId(id);
        redisTemplate.opsForValue().set(TEST_VALUE_KEY + id, JSON.toJSONString(test));
        return id;
    }
}
